package org.myhibernate.excel;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.myhibernate.core.Mapping;
import org.myhibernate.core.Mappings;
import org.myhibernate.core.Template;
import org.myhibernate.util.ObjectUtil;


public class ExcelImport  
{
	private Class cls=null;
	private String excelPath="";
	private Map<String,String> excelColToObjectMap=null;
	private List<Map<String,String>> dataList=null;
	private ExcelMap excelMap=null;
	private String defaultValue="0";
	public ExcelImport(Class cls, String excelPath,ExcelMap excelMap) 
	{
		this.cls = cls;
		this.excelPath = excelPath;
		this.excelMap=excelMap;
		this.excelColToObjectMap = excelMap.getMap(); 
		
	}
	public ExcelImport(Class cls, String excelPath,String fileTitle) 
	{
		String simpleName=fileTitle.substring(0,fileTitle.lastIndexOf("."));
		ExcelMap emap=ExcelMaps.getExcelMap(simpleName);
		this.cls = cls;
		this.excelPath = excelPath;
		this.excelMap=emap;
		this.excelColToObjectMap = emap.getMap(); 
		
	}
	public ExcelImport(Class cls, String excelPath,Map<String, String> excelColToObjectMap) 
	{
		this.cls = cls;
		this.excelPath = excelPath;
		this.excelColToObjectMap = excelColToObjectMap; 
	}
	public int impt(Map<String, String> addtionalFieldMap)throws Exception
	{
		int count=0;
		File excelFile=new File(excelPath);
		if (excelFile.exists()==false) {
			throw new RuntimeException("Not found file:  "+excelPath);
		}
		ExcelReader reader=new ExcelReader();
		dataList= reader.readReturnMapInList(excelPath);
		//System.out.println("dataList="+dataList);
		count=dataList.size();
		if (count==0) {
			return count;
		}
		Template template=new Template(cls);
		try 
		{
			List objectList=new ArrayList();
			ObjectUtil objectUtil=new ObjectUtil();
			Mapping mapping=Mappings.getMapping(getCls());
			String idField=mapping.getId_Field();
			for (int i = 0; i < dataList.size(); i++) 
			{
				//获取到excel中数据 ，一行的map
				Map dataMap=dataList.get(i);
				//System.out.println("dataMap="+dataMap);
				//System.out.println("excelMap="+excelColToObjectMap);
				//System.out.println("addtionalMap="+addtionalFieldMap);
				//如果附加属性的map不为空，则添加进去
				if (addtionalFieldMap!=null)
				{
					Iterator<String> iterator=addtionalFieldMap.keySet().iterator();
					while(iterator.hasNext())
					{
						Object key=iterator.next();
						dataMap.put(key+"", addtionalFieldMap.get(key)+"");
					}
				}
				boolean hasId=false;
				StringBuffer idValue=new StringBuffer();//id标识以uid和日期年月组成
				String dateTime="";
				//if (dataMap.containsKey(idField)) 
				//判断是否有id
				if(excelMap.hasId())
				{
					hasId=true;
					String idFields=excelMap.getIdTitle();
					//idValue=dataMap.get(idField)+"";
					String[] fs=idFields.split(",");
					for (int j = 0; j < fs.length; j++) 
					{
						if (j == 0) 
						{
							idValue.append(dataMap.get(fs[j]));
						} else 
						{
							idValue.append("_"+dataMap.get(fs[j]));
						}
					}
					dataMap.put(excelMap.getIdField(), idValue.toString()+"");
				}
				//把excel映射字段，映射进数据行map里面去
				if (excelColToObjectMap !=null)
				{
					Iterator<String> iterator=excelColToObjectMap.keySet().iterator();
					String excelColName="";
					String excelColData="";
					String objectFieldName="";
					while(iterator.hasNext())
					{
						excelColName=iterator.next();
						objectFieldName=excelColToObjectMap.get(excelColName);
						excelColData=dataMap.get(excelColName)+"";
						if (("null".equals(excelColData))||("".equals(excelColData)))
						{
							excelColData=defaultValue;
						}
						if (excelColData!=null)
						{
							dataMap.put(objectFieldName, excelColData);
						}
					}//endwhile
				}//if
				
				//创建数据对象
				Object object=null;
				try {
					if (hasId) 
					{
						object=template.get(idValue);
					} else 
					{
						object=Class.forName(getCls().getName()).newInstance();
						
					}
					if (object==null) {
						object=Class.forName(getCls().getName()).newInstance();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				//System.out.println("dataMap="+dataMap);
				//设置数据对象的值
				objectUtil.setObjectData(object, dataMap);
				//保存或者更新数据对象
				if (hasId)
				{
					if (template.get(idValue)==null) 
					{
						template.save(object);
					} else {
						template.update(object);
					}
				} else
				{
					template.save(object);
				}
			
			}//endfor
			//template.save(objectList);
		} catch (Exception e) 
		{
			e.printStackTrace();
			throw new RuntimeException("Runtime exception:"+e.toString());
		}
		finally{
			if (template!=null) {
				template.close();
			}
		}
		return count;
	}
	public List<Map<String, String>> getDataList() {
		return dataList;
	}
	public Class getCls() {
		return cls;
	}
	public String getExcelPath() {
		return excelPath;
	}
	public Map<String, String> getExcelColToObjectMap() {
		return excelColToObjectMap;
	}
	public String getDefaultValue() {
		return defaultValue;
	}
	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}
}
